<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('account.fields.accountType')" prop="accountType">
        <el-select
          v-model="queryParams.accountType"
          :placeholder="t('common.selectTextPlaceholder') + t('account.fields.accountType')"
          clearable
          @change="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        >
          <el-option :label="t('accountSelect.state.type1')" :value="1" />
          <el-option :label="t('accountSelect.state.type2')" :value="2" />
          <el-option :label="t('accountSelect.state.type3')" :value="3" />
          <el-option :label="t('accountSelect.state.type4')" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('account.fields.username')" prop="username">
        <el-input
          v-model="queryParams.username"
          :placeholder="t('common.inputTextPlaceholder') + t('account.fields.username')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('account.fields.phone')" prop="phone">
        <el-input
          v-model="queryParams.phone"
          :placeholder="t('common.inputTextPlaceholder') + t('account.fields.phone')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('account.fields.nickname')" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          :placeholder="t('common.inputTextPlaceholder') + t('account.fields.nickname')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" :disabled="advancedSearching">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery" :disabled="advancedSearching">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <ConditionTree
          id="account-condition-tree"
          :schemata="accountSchema"
          @search="handleAdvanceSearch"
        />
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iAccount-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('account.fields.accountType')"
        field="accountType"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.accountType === 1" disable-transitions>{{
            t('accountSelect.state.type1')
          }}</el-tag>
          <el-tag v-if="scope.row.accountType === 2" disable-transitions>{{
            t('accountSelect.state.type2')
          }}</el-tag>
          <el-tag v-if="scope.row.accountType === 3" disable-transitions>{{
            t('accountSelect.state.type3')
          }}</el-tag>
          <el-tag v-if="scope.row.accountType === 4" disable-transitions>{{
            t('accountSelect.state.type4')
          }}</el-tag>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('account.fields.username')"
        field="username"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('account.fields.phone')"
        field="phone"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('account.fields.nickname')"
        field="nickname"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('account.fields.avatar')"
        field="avatar"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-image
            class="student-avatar"
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
            fit="cover"
          />
        </template>
      </vxe-column>

      <vxe-column
        :title="t('account.fields.activated')"
        field="activated"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-tag disable-transitions v-if="scope.row.activated" type="success"
            >{{ t('accountSelect.state.activated') }}
          </el-tag>
          <el-tag disable-transitions v-else>{{ t('accountSelect.state.inactivated') }}</el-tag>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('account.fields.status')"
        field="status"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-tag disable-transitions v-if="scope.row.status === 0" type="success"
            >{{ t('accountSelect.state.enabled') }}
          </el-tag>
          <el-tag disable-transitions v-if="scope.row.status === 1"
            >{{ t('accountSelect.state.disabled') }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('account.fields.loginIp')"
        field="loginIp"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('account.fields.loginDate')"
        field="loginDate"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('account.fields.remark')"
        field="remark"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('account.fields.createTime')"
        field="createTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="140"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:account:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:account:delete']"
          >
            {{ t('action.delete') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AccountForm ref="formRef" @success="getList" />
  <ExcelImportForm
    ref="importFormRef"
    object-name="账号信息"
    upload-url="/system/account/import"
    template-url="/system/account/get-import-template"
    @success="getList"
  />
</template>

<script setup lang="ts">
import { vxeDateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AccountApi, AccountVO } from '@/api/system/account'
import AccountForm from './AccountForm.vue'
import ExcelImportForm from '@/components/ExcelImportForm/index.vue'
import type { VxeTablePropTypes, VxeToolbarInstance, VxeTableInstance } from 'vxe-table'
import { accountSchema } from '@/views/system/account/schema'
import { useAppStore } from '@/store/modules/app'

/** 账号信息 列表 */
defineOptions({ name: 'Account' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<AccountVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const advancedSearching = ref(false) // 高级搜索
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  advanced: undefined,
  username: undefined,
  password: undefined,
  phone: undefined,
  nickname: undefined,
  avatar: undefined,
  accountType: undefined,
  remark: undefined,
  activated: undefined,
  status: undefined,
  loginIp: undefined,
  loginDate: [],
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AccountApi.getAccountPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  advancedSearching.value = false
  ;(queryParams as any).advanced = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof AccountForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 导入 */
const importFormRef = ref<InstanceType<typeof ExcelImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AccountApi.deleteAccount(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AccountApi.exportAccount(queryParams)
    download.excel(data, '账号信息.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleAdvanceSearch = (base64Advanced?: string) => {
  ;(queryParams as any).advanced = base64Advanced
  advancedSearching.value = !!base64Advanced
  handleQuery()
}

/** 初始化 **/
onMounted(() => {
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
.student-avatar {
  width: 80px;
  height: 80px;
  display: block;
  margin: 5px auto;
  border-radius: 6px;
}
</style>
